<script lang="ts">
	import Button, { Label } from '@smui/button';
	import PreBuyProduct from './_com/PreBuyProduct.svelte';
	import { getCartStore } from '@/store/modules/cart';
	import { onMount } from 'svelte';
	import { get } from 'svelte/store';
	import { alova } from '$utils/request';
	import { price_transform } from '$utils/filter';
	import { createMessage, showLoading } from '$components/basic/message';
	import { getPreOrderStore } from '@/store/modules/pre';
	import { goto } from '$utils/intercept';
	import { useUserstore } from '@/store';
	import Empty from '$lib/empty/cartEmpty.svg';
	// import Divider from '$components/basic/divider/divider.svelte';
	// import { handleReq } from '@/hooks/handleReq';

	let list: IObject[] = [];
	let group: IObject = {};

	const CartStore = getCartStore();
	const preOrderStore = getPreOrderStore();
	const init = async () => {
		CartStore.cartList.subscribe((value) => (list = value));
		const split_obj = (i) => ({ itemId: i.id, num: i.num, created_at: i.created_at });
		const items = get(CartStore.cartList).map(split_obj);
		const res = await alova.Post('/member-cart/list', { items });
		const filterFunc = (i) => i.mask == 1; // 只保留mask为1的项
		CartStore.mergeList((res as any).data || [], filterFunc);
		get(CartStore.cartList).forEach((i) => (group[String(i.id)] = false));
	};
	onMount(init);

	const postDelete = async (itemId: number[]) =>
		await alova.Post('/member-cart/delete', { itemId });
	const deleteItem = async (event: CustomEvent) => {
		const msg = showLoading();
		try {
			await postDelete([event.detail.id]);
			CartStore.removeCartItem(event.detail.id);
			msg.close();
		} catch (error) {
			msg.error();
		}
	};
	const updateItemNum = (event: CustomEvent) => CartStore.addCartItem(event.detail);
	const checkAll = () => Object.keys(group).forEach((i) => (group[i] = true));
	const emptyCart = async () => {
		const msg = showLoading();
		try {
			await postDelete(Object.keys(group).map((i) => Number(i)));
			CartStore.clearAllCarts();
			msg.close();
		} catch (error) {
			msg.error();
		}
	};

	const place_order = async () => {
		if (!Object.keys(group).filter((i) => group[i]).length) {
			createMessage({ type: 'warning', message: 'Please select the items first' });
			return;
		}

		if (get(useUserstore().token) === '') {
			createMessage({ type: 'danger', message: 'Please login first' });
			return goto('/login');
		}

		preOrderStore.setPreOrders(Object.keys(group).filter((i) => group[i]));
		goto('/order/confirm');
	};

	$: amount = list.reduce((acc, cur) => acc + (group[String(cur.id)] ? cur.num * cur.price : 0), 0);
</script>

<div class="w-full p-20px flex-cc">
	<div class="w-1320px min-w-350px max-w-100% flex flex-col gap-20px">
		<!-- <Divider direction="horizontal" style="--mdc-theme-primary: #d1d5db " /> -->
		{#if list.length}
			<div class="flex flex-row justify-start items-center gap-10px">
				<Button variant="raised" on:click={checkAll}>CheckAll</Button>
				<Button on:click={emptyCart} variant="raised" style="background-color: #999;">
					<Label>Empty Cart</Label>
				</Button>
			</div>
		{/if}

		{#each list as item}
			<PreBuyProduct
				bind:group
				info={item}
				on:deleteItem={deleteItem}
				on:updateItemNum={updateItemNum}
			/>
		{/each}

		{#if list.length}
			<div
				class="w-full bg-red-1 p-15px h-60px line-height-60px flex flex-row items-center gap-10px shadow-gray-3 shadow color-#555"
			>
				<div class="flex flex-row gap-10px font-bold">
					<span>Total Amount: </span><span>USD</span><span class="color-red-7"
						>{price_transform(amount)}</span
					>
				</div>
			</div>
			<div class="flex flex-row justify-end">
				<Button
					class="w-40% color-white! h-60px line-height-60px"
					variant="raised"
					on:click={place_order}>Place Order</Button
				>
			</div>
		{/if}

		{#if !list.length}
			<div class="w-full flex-cc">
				<img src={Empty} alt="no items" />
			</div>
		{/if}
	</div>
</div>

<style>
	.home-button {
		display: inline-block;
		padding: 4px 20px;
		font-size: 16px;
		color: white;
		background-color: var(--mdc-theme-primary); /* Button color */
		border: none;
		border-radius: 5px; /* Rounded corners */
		text-decoration: none; /* Remove underline */
		transition: background-color 0.3s;
	}

	.home-button:hover {
		background-color: color-mix(
			in srgb,
			var(--mdc-theme-primary) 60%,
			white
		); /* Darker shade on hover */
		box-shadow:
			0 1px 2px rgba(0, 0, 0, 0.2),
			0 2px 4px rgba(0, 0, 0, 0.1),
			0 4px 8px rgba(0, 0, 0, 0.1);
	}
</style>
